package com.passion.plugins;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.passion.common.enums.BaseEnums;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 类描述：字段属性填充处理器
 *
 * @author ZhuYin
 * @since 2024年08月13日
 */
@Component
public class FieldMetaObjectHandler implements MetaObjectHandler {

    /**
     * 方法说明：表实体类字段标注了 @TableField(fill = FieldFill.INSERT) 的填充逻辑
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        String createTimeStr = "createTime";
        String createDateStr = "createDate";
        String delFlagStr = "delFlag";

        // 非登录状态字段填充
        if (metaObject.hasSetter(createTimeStr)) {
            this.setFieldValByName(createTimeStr, new Date(), metaObject);
        }
        if (metaObject.hasSetter(delFlagStr)) {
            this.setFieldValByName(delFlagStr, BaseEnums.DelFlag.NORMAL.getCode(), metaObject);
        }
        if (metaObject.hasSetter(createDateStr)) {
            Class<?> createDateClass = metaObject.getSetterType(createDateStr);
            if (String.class.equals(createDateClass)) {
                String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                setFieldValByName(createDateStr, timeStr, metaObject);
            }
            if (Date.class.equals(createDateClass)) {
                setFieldValByName(createDateStr, new Date(), metaObject);
            }
        }
    }

    /**
     * 方法说明：表实体类字段标注了 @TableField(fill = FieldFill.INSERT_UPDATE) 或 @TableField(fill = FieldFill.UPDATE) 的填充逻辑
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        String updateTimeStr = "updateTime";
        String updateDateStr = "updateDate";
        // 非登录状态字段填充
        if (metaObject.hasSetter(updateTimeStr)) {
            setFieldValByName(updateTimeStr, new Date(), metaObject);
        }
        if (metaObject.hasSetter(updateDateStr)) {
            Class<?> updateDateClass = metaObject.getSetterType(updateDateStr);
            String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            if (String.class.equals(updateDateClass)) {
                setFieldValByName(updateDateStr, timeStr, metaObject);
            }
            if (Date.class.equals(updateDateClass)) {
                setFieldValByName(updateDateStr, new Date(), metaObject);
            }
        }
    }

}
